import Vue from 'vue';
import Store from 'src/store';
import {userMessage} from "src/lib/util/message";
import {i18n} from 'src/boot/i18n';

const Box = {
  upload: async () => {
    const box = Store.getters['box/box'];
    let {data} = await Vue.prototype.$axios.post('api/box/upload', {
      username: Store.state.account.username,
      token: Store.state.account.token,
      box
    });
    if (data.result) {
      userMessage('success', '成功上传box信息到服务器。');
      return true;
    } else {
      userMessage('error',  i18n.t(data.error) || '发生了一些错误，请稍后再试。');
      if (data.error === 'ERR_TOKEN_INVALID' || data.error === 'ERR_TOKEN_EXCEEDED') {
        Store.commit('account/remove');
        window.location.href = "/account";
      }
    }
    return false;
  },
  download: async () => {
    let {data} = await Vue.prototype.$axios.post('api/box/download', {
      username: Store.state.account.username,
      token: Store.state.account.token
    });
    if (data.result) {
      userMessage('success', '成功下载box信息到本地。');
      return data.data;
    } else {
      userMessage('error', i18n.t(data.error) || '发生了一些错误，请稍后再试。');
      if (data.error === 'ERR_TOKEN_INVALID' || data.error === 'ERR_TOKEN_EXCEEDED') {
        Store.commit('account/remove');
        window.location.href = "/account";
      }
    }
    return null;
  }
}

export default Box;
